<template>
  <div class="home">
    <pre>result:{{ result }}</pre>
    <br />
    <label>username:</label>
    <input type="text" v-model="user.username" /> <br />
    <label>password:</label>
    <input type="text" v-model="user.password" /> <br /><br />
    <input
      type="button"
      value="发送简单得异步请求-get"
      @click="sendRequest()"
    />
    <input
      type="button"
      value="发送简单得异步请求-post"
      @click="sendRequest2()"
    />
    <br />
    <input type="button" value="真实登录操作" @click="login()" />
    <input type="button" value="真实登录操作-带拦截器" @click="login2()" />
  </div>
</template>

<script>
import { testQuery, testBody } from "../api/test";
import { doLogin } from "../api/real";
import { doLogin2 } from "../api/real2.js";
export default {
  name: "HomeView",
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      result: {},
    };
  },
  methods: {
    async sendRequest() {
      try {
        let { data } = await testQuery(this.user);
        this.result = data;
      } catch (error) {
        alert("请求错误");
      }
    },
    async sendRequest2() {
      try {
        let { data } = await testBody(this.user);
        this.result = data;
      } catch (error) {
        alert("请求错误");
      }
    },
    async login() {
      try {
        let response = await doLogin(this.user);
        console.log(response);
        // 判断业务是否成功
        if (response.data.code != 200) {
          alert(response.data.msg);
          return;
        }
        // 将token存到vuex中
        this.$store.commit("setToken", response.data.token);

        // console.log("跳转到首页");
        this.$router.push({
          name: "about",
        });
      } catch (error) {
        // 判断请求是否成功
        console.log(error);
        // alert(error.message);
        alert("请求失败");
      }
    },
    async login2() {
      let { token } = await doLogin2(this.user);
      console.log(token);
      this.$store.commit("setToken", token);
      // 请求成功登录成功后才可以跳转页面
      this.$router.push({
        name: "about",
      });
    },
  },
};
</script>
